package com.cyc.basic.view;

import java.util.Arrays;

/**
 * @Description: 找到两个有序数组的交集
 * @version 1.0
 * @author cyc
 * @date 2021/10/8 10:23
 */
public class BossTest {

}

class Solution {

    public static int[] findIntersection(int[] array1, int[] array2) {
        int length1 = array1.length, length2 = array2.length;
        int[] intersectionArray = new int[length1 + length2];
        int index = 0;//新数组的索引
        int index1 = 0, index2 = 0;
        while (index1 < length1 && index2 < length2) {
            //当其中一个数组的下标达到最后一位时, 就停止循环, 查找完成
            int num1 = array1[index1];
            int num2 = array2[index2];
            if (num1 == num2) {
                if (index == 0 || num1 != intersectionArray[index - 1]) {
                    //处理边界,新值不等于上一个值就添加
                    intersectionArray[index++] = num1;
                }
                index1++;
                index2++;
            } else if (num1 < num2) {
                index1++;
            } else {
                index2++;
            }
        }
        return Arrays.copyOfRange(intersectionArray, 0, index);
    }

    public static void main(String[] args) {
        char[] chars1 = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
//        char[] chars2 = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
        char[] chars2 = {'a', 'b', 'c', 'd', 'f', 'g'};
        char c = find(chars1, chars2);

        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = {2, 3, 4, 5};
        int[] intersection = findIntersection(arr1, arr2);
        System.out.println(Arrays.toString(intersection));

        System.out.println(c);

        Arrays.sort(arr1);
    }

    public static char find(char[] chars1, char[] chars2) {
        int index1 = 0, index2 = 0;
        int length1 = chars1.length, length2 = chars2.length;
        char c = 0;
        while (index1 < length1 && index2 < length2) {
            char c1 = chars1[index1];
            char c2 = chars2[index2];
            if (c1 == c2) {
                index1++;
                index2++;
            } else {
                if (c1 < c2) {
                    c = c1;
                    break;
                } else {
                    c = c2;
                    break;
                }
            }
        }
        return c;
    }
}
